var vmContainer = new Vue({
    el: "#container",
    data: {
        // 当前目录ID
        currentDirectoryId: '0',
        // 面包屑导航
        directList: [],
        // 文件列表
        fileList: [],
        // 重命名的id
        editId: '',
        // 修改之后的文件夹或文件的名字
        editName: '',
        // 需要显示全名的文件
        showId: ''
    },
    methods: {
        newFolder: function () {
            //
            var newFolderTpl = document.getElementById('newFolder').innerHTML;
            layui.laytpl(newFolderTpl).render({folderName: "文件夹"}, function (html) {
                var cmd = new POPUP.Cmd("新建文件夹", ["320px", "180px"], html);
                cmd.dialog(function () {
                    var folderName = $("#folderName").val();
                    if (folderName.length > 0) {
                        var r = false;
                        postAjax(_ctx + "/folder/new", {
                            parentId: vmContainer.currentDirectoryId,
                            folderName: folderName
                        }, function (result) {
                            if (result.success) {
                                r = true;
                                loadFiles(vmContainer.currentDirectoryId); // 重载文件列表
                                layui.layer.msg(result.message);
                            } else {
                                layui.layer.alert(result.message, {icon: 5});
                            }
                        }, false);
                        return r;
                    } else {
                        layui.layer.alert("文件夹名必须填写", {icon: 0});
                    }
                });
                layui.form.render();
            });
        },
        uploadFile: function () {
            var upLoadFileTpl = document.getElementById('upLoadFileList').innerHTML;
            layui.laytpl(upLoadFileTpl).render({}, function (html) {
                var cmd = new POPUP.Cmd("上传文件", ["600px", "400px"], html);
                cmd.setBtn(["关闭窗口"]);
                cmd.dialog(function () {
                    loadFiles(vmContainer.currentDirectoryId);
                    return true;
                });

                var demoListView = $('#fileList'),
                    uploadListIns = layui.upload.render({
                        elem: '#selectList'
                        , url: _ctx + '/server/data'
                        , accept: 'file'
                        , multiple: true
                        , auto: false
                        , bindAction: '#uploadAction'
                        , choose: function (obj) {
                            var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列
                            //读取本地文件
                            obj.preview(function (index, file, result) {
                                var tr = $(['<tr id="upload-' + index + '">'
                                    , '<td>' + file.name + '</td>'
                                    , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                                    , '<td>等待上传</td>'
                                    , '<td>'
                                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                                    , '</td>'
                                    , '</tr>'].join(''));

                                //单个重传
                                tr.find('.demo-reload').on('click', function () {
                                    obj.upload(index, file);
                                });

                                //删除
                                tr.find('.demo-delete').on('click', function () {
                                    delete files[index]; //删除对应的文件
                                    tr.remove();
                                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                                });

                                demoListView.append(tr);
                            });
                        }
                        , done: function (res, index, upload) {
                            if (res.success) { //上传成功
                                postAjax(_ctx + "/files/saveFile", {
                                    folderId: vmContainer.currentDirectoryId,
                                    fileName: res.orgFileName,
                                    filePath: res.loadPath,
                                    fileSize: res.fileSize,
                                    fileCode: res.code
                                }, function (result) {
                                    console.log(result);
                                });
                                var tr = demoListView.find('tr#upload-' + index)
                                    , tds = tr.children();
                                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                                tds.eq(3).html(''); //清空操作
                                return delete this.files[index]; //删除文件队列已经上传成功的文件
                            }
                            this.error(index, upload);
                        }
                        , error: function (index, upload) {
                            var tr = demoListView.find('tr#upload-' + index)
                                , tds = tr.children();
                            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
                        }
                    });
            });
        },
        jumpTo: function (directoryId, ftype) { // 跳转至指定文件夹下
            if (directoryId === this.currentDirectoryId) {
                return false;
            }
            if (ftype === "0") {
                this.currentDirectoryId = directoryId;
                loadFiles(directoryId);
                loadBreadCrumb(); // 加载面包屑
            }
        },
        showName: function (fileId) {
            this.showId = fileId;
        },
        /**
         * 返回上一级
         */
        backLast: function () {
            if (this.directList.length >= 2) {
                var backId = this.directList[this.directList.length - 2].id;
                this.jumpTo(backId, '0')
            }
        },
        /**
         * 右键菜单
         * @param $event
         * @param id
         * @param fileName
         * @param fType
         */
        rightMenu: function ($event, id, fileName, fType) {
            vmContextMenu.show = true;
            vmContextMenu.top = $event.pageY;
            vmContextMenu.left = $event.pageX;

            vmContextMenu.selected.fileId = id;
            vmContextMenu.selected.fileName = fileName;
            vmContextMenu.selected.fType = fType;
        },
        hideRightMenu: function () {
            vmContextMenu.show = false;
        },
        nullOperate: function () {

        },
        closeEdit: function () {
            this.showId = '';
            if (this.editId) {
                postAjax(_ctx + "/files/rename", {
                    fileId: this.editId,
                    fileName: this.editName,
                    fType: vmContextMenu.selected.fType
                }, function (result) {
                    if (result.success) {
                        loadFiles(vmContainer.currentDirectoryId);
                        vmContainer.editId = '';
                        vmContainer.editName = '';
                    } else {
                        layui.layer.alert(result.message, {icon: 0});
                    }
                });
            }
        },
        cancelEdit: function () {
            this.showId = '';
            this.editId = '';
            this.editName = '';
        }
    },
    watch: {
        'editId': function (n, o) {
            selectInput(n);
        }
    }
});

// 右键菜单
var vmContextMenu = new Vue({
    el: '#right-menu',
    data() {
        return {
            show: false,
            top: 0,
            left: 0,
            selected: {
                fileId: '',
                fileName: '',
                fType: ''
            }
        }
    },
    methods: {
        download() {
            alert(this.selected.fileId + "下载" + this.selected.fType);
            vmContainer.hideRightMenu();
        },
        moveTo() {
            alert("移动文件");
            vmContainer.hideRightMenu();
        },
        copyTo() {
            alert("复制文件");
            vmContainer.hideRightMenu();
        },
        rename() {
            vmContainer.editId = this.selected.fileId;
            vmContainer.editName = this.selected.fileName;
            vmContainer.hideRightMenu();
        }
    }
});

loadFiles(0);
loadBreadCrumb();


//执行一个laypage实例
layui.laypage.render({
    elem: 'page-tool',
    layout: ["prev", "page", "next"],
    count: 1000, //数据总数，从服务端得到
    limit: 30,
    limits: [30, 60, 120, 300, 500],
    jump: function (obj, first) {
        //obj包含了当前分页的所有参数，比如：
        console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
        console.log(obj.limit); //得到每页显示的条数

        //首次不执行
        if (!first) {
            //do something
        }
    }
});

// 渲染进度条和面包屑导航
layui.element.render();

function selectInput(editId) {
    setTimeout(function () {
        if (editId) {
            var inputs = $(".file-item").find("input");
            if (inputs.length > 0) {
                inputs.eq(0).select();
            }
        }
    }, 100);
}

// 加载文件列表
function loadFiles(parentId) {
    var loadIndex = layer.msg("正在加载数据...");
    postAjax(_ctx + "/userFile/fileList", {parentId: parentId}, function (result) {
        if (result.success) {
            vmContainer.fileList = result.data;
        } else {
            layer.alert(result.message);
        }
        layer.close(loadIndex);
    });
}

/**
 * 重新加载面包屑导航
 */
function loadBreadCrumb() {
    postAjax(_ctx + "/folder/parentList", {
        currentDirectoryId: vmContainer.currentDirectoryId
    }, function (result) {
        if (result.success) {
            vmContainer.directList = result.data;
            layui.element.render();
        } else {
            layer.alert(result.message);
        }
    });
}

$('.census').hover(function () {
    layer.tips("文件数量: 132<br>文件夹数量: 50", '.census', {
        time: 6000,
        tips: [1, "#3c3c3c"]
    })
}, function () {
    layui.layer.closeAll('tips');
});